import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MethodChannelDemo extends StatefulWidget {
  const MethodChannelDemo({super.key});

  @override
  MethodChannelDemoState createState() => MethodChannelDemoState();
}

class MethodChannelDemoState extends State<MethodChannelDemo> {
  // 初始化 MethodChannel
  var channel = const MethodChannel("com.flutter.guide.MethodChannel");
  String _data = '';
  String _nativeData = '';

  @override
  void initState() {
    super.initState();
    //监听并接收原生数据
    channel.setMethodCallHandler((MethodCall call) async {
      debugPrint("$call");
      if (call.method == "sendData2") {
        setState(() {
          var name = call.arguments["name"];
          var age = call.arguments["age"];
          _nativeData = '$name,$age';
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('MethodChannel'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          const SizedBox(
            height: 50,
          ),
          ElevatedButton(
            onPressed: () async {
              //向原生端 发送数据
              var result = await channel
                  .invokeMethod('sendData', {'name': 'Jack', 'age': 18});
              var name = result['name'];
              var age = result['age'];

              debugPrint("--原生返回的数据---$result");
              setState(() {
                _data = '$name,$age';
              });
            },
            child: const Text('发送数据到原生'),
          ),
          Text('原生返回数据：$_data'),
          Text('接收到原生返回数据：$_nativeData')
        ],
      ),
    );
  }
}
